package model;

import ecom.beans.AccountBean;
import ecom.beans.EcomCustomerRemote;
import ecom.shell.ShellRemote;

/**
 *
 * @author Sebastien
 */
public class Cart extends AbstractPage {

    public String addOrRemove() throws Exception {
        //RECUPERATION DU SHELL
        ShellRemote shell = (ShellRemote) getSession().get("shell");

        String[] id_store = (String[]) this.getParameters().get("id_store");
        String[] id_product = (String[]) this.getParameters().get("id_product");
        String[] quantity = (String[]) this.getParameters().get("quantity");
        String[] action = (String[]) this.getParameters().get("action");

        if (id_store != null && !"".equalsIgnoreCase(id_store[0]) &&
                id_product != null && !"".equalsIgnoreCase(id_product[0]) &&
                quantity != null && !"".equalsIgnoreCase(quantity[0]) &&
                action != null && !"".equalsIgnoreCase(action[0])) {
            EcomCustomerRemote remoteBean = (EcomCustomerRemote) getSession().get("customerRemote");
            if ("add".equals(action[0])) {
                remoteBean.addProductToCart(Integer.valueOf(id_product[0]), Integer.valueOf(id_store[0]), Integer.valueOf(quantity[0]));
            } else {
                remoteBean.removeProductInCart(Integer.valueOf(id_product[0]), Integer.valueOf(id_store[0]), Integer.valueOf(quantity[0]));
            }
        //shell.executeCommand("cart -" + action[0] + " .p " + id_product[0] + " .s " + id_store[0] + " .q " + quantity[0]);
        }
        return "redirectToReferrer";
    }

    public String showDetail() throws Exception {
        this.setPage("cart.jsp");
        return SUCCESS;
    }

    public String buy() throws Exception {
        AccountBean user = (AccountBean) getSession().get("user");
        if (user == null) {
            throw new Exception("Please, log in to do that !");
        }
        EcomCustomerRemote remoteBean = (EcomCustomerRemote) getSession().get("customerRemote");
        double total = remoteBean.buyCart(user.getAccountId());
        user.withdraw(total);
        this.setPage("cart_bought.jsp");
        return SUCCESS;
    }
}
